package test6;


/**
 * @title: 有效括号长度
 * @description:
 * @Author 易俊杰
 * @data: 2022/7/30 10:20
 * @version: V1.0
 */
public class Demo5 {
    public static void main(String[] args) {
        System.out.println(longestValidParentheses("(()())"));

    }

    public static int longestValidParentheses(String s) {
        int max = 0;
        int[] dp = new int[s.length()];
        for (int i = 1; i < s.length(); i++) {
            char c = s.charAt(i);
            if (c == ')') {
                if (dp[i - 1] == 0) {
                    if (s.charAt(i - 1) == '(') {
                        if (i - 2 >= 0) {
                            dp[i] = dp[i - 2] + 2;
                        } else {
                            dp[i] = 2;
                        }
                    }
                } else {
                    int index = i - 1 - dp[i - 1];
                    if (index >= 0 && s.charAt(index) == '(') {
                        if (index - 1 >= 0) {
                            dp[i] = dp[i - 1] + dp[index - 1] + 2;
                        } else {
                            dp[i] = dp[i - 1] + 2;
                        }
                    }
                }
                if (max < dp[i]) {
                    max = dp[i];
                }
            }
        }
        return max;
    }
}
